package com.guoxin.mashibing;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockTest {

    public static void main(String[] args) {
        final Lock lock = new ReentrantLock();

        Thread t1 = new Thread("T1") {
            @Override
            public void run() {
                lock.lock();
                try {
                    System.out.println("T1 start");
                    for (int i = 0; i < 10; i++) {
                        System.out.println(Thread.currentThread().getName() + "---" + i);
                        TimeUnit.SECONDS.sleep(1);
                    }
                } catch (InterruptedException e) {
                    System.out.println("----interrupted");
                } finally {
                    lock.unlock();
                }
            }
        };

        Thread t2 = new Thread("T2") {
            @Override
            public void run() {
                try {
                    lock.lockInterruptibly();
                    System.out.println("T2 start");
                    TimeUnit.SECONDS.sleep(3);
                    System.out.println("T2 end");
                } catch (InterruptedException e) {
                    System.out.println("----interrupted");
                } finally {
                    if (((ReentrantLock) lock).isLocked()) {
                        lock.unlock();
                    }
                }
            }
        };

        t1.start();
        t2.start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.interrupt();
    }
}
